package org.yiqixue.accounts.controller;

import org.yiqixue.accounts.dto.TransactionDTO;
import org.yiqixue.accounts.service.TransactionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@RestController
@RequestMapping("/transactions")
public class TransactionController {

    @Autowired
    private TransactionService transactionService;

    // 日期格式常量
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    // 根据手机号和交易类型查询当天的所有交易
    @GetMapping("/by-phone-and-type")
    public List<TransactionDTO> getTransactionsByPhoneAndType(
            @RequestParam String phoneNumber,
            @RequestParam String type,
            @RequestParam String date) {

        // 将日期字符串转换为 LocalDate
        LocalDate queryDate = LocalDate.parse(date, DATE_FORMATTER);

        // 设置查询时间范围（当天开始到结束）
        LocalDateTime startDate = queryDate.atStartOfDay();  // 00:00:00
        LocalDateTime endDate = queryDate.atTime(LocalTime.MAX);  // 23:59:59.999999999

        return transactionService.getTransactionsByCustomerPhoneAndType(
                phoneNumber,
                type,
                startDate,
                endDate
        );
    }

    // 创建新的交易记录
    @PostMapping
    public ResponseEntity<TransactionDTO> createTransaction(@RequestBody TransactionDTO transactionDTO) {
        // 如果前端传的是字符串时间，可以在这里转换
        if (transactionDTO.getTransactionDate() == null) {
            transactionDTO.setTransactionDate(LocalDateTime.now());
        }

        TransactionDTO createdTransaction = transactionService.createTransaction(transactionDTO);
        return ResponseEntity.ok(createdTransaction);
    }
}